const app = getApp();

const api = require('./api.js');

var url = api.webSocketChat; //webSocket连接 {reserveRecordId}/{identityId}  +this.data.reserveRecordId+"/"+wx.getStorageSync("identityId")

function connect(user, func) {
    var _url = 'wss://shareparking.wasu.cn:9443' + user; //ws://112.124.1.208:34567   wss://shareparking.wasu.cn:8888

    uni.connectSocket({
        url: _url,
        header: {
            'content-type': 'application/json'
        },
        success: function () {
        },
        fail: function () {
        }
    });
    uni.onSocketOpen(function (res) {
        //  wx.showToast({
        //   title: 'websocket已开通~',
        //   icon: "success",
        //   duration: 2000
        //  })
        let body = {};
        body.key = 'client_bind';
        body.timestamp = new Date().getTime();
        body.data = {};
        body.data.uid = uni.getStorageSync('identityId');
        body.data.channel = 'web';
        body.data.appVersion = '1.0.0';
        body.data.packageName = 'com.farsunset.cim';
        let d = new Date().getTime();
        let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            let r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
        });
        body.data.deviceId = uuid.replace(/-/g, '');
        body.data.deviceName = 'other';
        let data = {};
        data.type = 3;
        data.content = JSON.stringify(body);
        uni.sendSocketMessage({
            data: JSON.stringify(data)
        }); // socket.send(JSON.stringify(data));
        //接受服务器消息

        uni.onSocketMessage(func); //func回调可以拿到服务器返回的数据
    });
    uni.onSocketError(function (res) {
        console.log('websocket连接失败，请检查！'); //  wx.showToast({
        //   title: 'websocket连接失败，请检查！',
        //   icon: "none",
        //   duration: 2000
        //  })
    });
} //发送消息

function send(msg) {
    uni.sendSocketMessage({
        data: msg
    });
}

module.exports = {
    connect: connect,
    send: send
};
